<?php
/**
 * 文档列表
 *
 */
// 加载公共文件
include dirname(__FILE__).'/global.php';
include_modules();

// 获取参数
$taxonomyid = isset($_GET['id']) ? intval(trim($_GET['id'])) : 0;
$page = isset($_GET['page']) ? intval(trim($_GET['page'])) : 1;

if (!$taxonomyid)
    die(__('Restricted access!'));
    
$taxonomy = taxonomy_get($taxonomyid);
if (!$taxonomy) {
    die(__('Restricted access!'));
}

$tpl    = tpl_init('taxonomy');
$page   = $page<1 ? 1 : intval($page);
$inner  = $b_guid = '';
$i = 0;
$suffix = C('HTML-Ext');
// 载入模版
$html   = tpl_loadfile(ABS_PATH.'/'.system_themes_path().'/'.$taxonomy['list']);
// 标签块信息
$block  = tpl_get_block($html,'post,list','list');
if ($block) {
    // 扩展字段过滤
    $meta    = tpl_get_attr($block['tag'],'meta');
    // 子分类ID
    $listsub = tpl_get_attr($block['tag'],'listsub');
    // 被排除的子分类ID
    $notsid  = tpl_get_attr($block['tag'],'listsub','!=');
    // 每页条数
    $number  = tpl_get_attr($block['tag'],'number');
    // 排序方式
    $order   = tpl_get_attr($block['tag'],'order');
    // 斑马线实现
    $zebra   = tpl_get_attr($block['tag'],'zebra');
    // 校验数据
    $listsub = $listsub == 'me' ? $listsub : validate_is($listsub, VALIDATE_IS_LIST) ? $listsub : null;
    $notsid  = validate_is($notsid,VALIDATE_IS_LIST) ? $notsid : null;
    $zebra   = validate_is($zebra,VALIDATE_IS_NUMERIC) ? $zebra : 0;
    $number  = validate_is($number,VALIDATE_IS_NUMERIC) ? $number : 10;
    $order   = instr(strtoupper($order),'ASC,DESC') ? $order : 'DESC';
    // 设置每页显示数
    pages_init($number, $page);
    $listids = array($taxonomyid);
    if ($listsub !== null) {
        // 查询IDs
        $listids = taxonomy_get_ids($taxonomyid, $listsub);
        // 排除IDs
        $notsids = $notsid ? explode(',', $notsid) : array();
        // 删掉排除的IDs
        foreach ($listids as $k=>$id) {
            if (in_array($id,$notsids))
                unset($listids[$k]);
        }
    }
    $length = count($listids);
    if ($length == 1) {
        $where = sprintf(" AND `tr`.`taxonomyid`=%d", array_pop($listids));
    } elseif ($length > 1) {
        $where = sprintf(" AND `tr`.`taxonomyid` IN(%s)", implode(',', $listids));
    }
    // 自定义字段
    if ($meta && (strpos($meta,':') !== false || strncasecmp($meta, 'find(', 5) === 0)) {
        // meta="find(value,field)"
        if (strncasecmp($meta, 'find(', 5) === 0) {
            $index = strrpos($meta, ',');
            $field = substring($meta, $index+1, strrpos($meta,')'));
            $value = substring($meta, 5, $index);
            $where.= sprintf(" AND FIND_IN_SET('%s', `pm`.`value`)", esc_sql($value));
        }
        // meta="field:value"
        elseif (($pos=strpos($meta,':')) !== false) {
            $field = substr($meta, 0, $pos);
            $value = substr($meta, $pos + 1);
            $where.= sprintf(" AND `pm`.`value`='%s'", esc_sql($value));
        }
        $sql = sprintf("SELECT DISTINCT(`tr`.`objectid`) AS `postid` FROM `#@_term_relation` AS `tr` LEFT JOIN `#@_post_meta` AS `pm` ON `tr`.`objectid`=`pm`.`postid` WHERE `pm`.`key`='%2\$s' %3\$s ORDER BY `objectid` %1\$s", $order, esc_sql($field), $where);
    } else {
        $where = str_replace('`tr`.', '', $where);
        // 拼装sql
        $sql = sprintf("SELECT `objectid` AS `postid` FROM `#@_term_relation` WHERE 1 %s ORDER BY `objectid` %s", $where, esc_sql($order));
    }
    $result = pages_query($sql);
    // 解析分页标签
    if (stripos($html,'{pagelist') !== false) {
        $html = preg_replace('/\{(pagelist)[^\}]*\/\}/isU',
            pages_list(ROOT.$taxonomy['path'].'/index$'.$suffix, '!$'),
            $html
        );
    }
    // 数据存在
    if ($result) {
        // 取得标签块内容
        $block['inner'] = tpl_get_block_inner($block);
        while ($data = pages_fetch($result)) {
            $post = post_get($data['postid']);
            if (empty($post)) continue;
            $post['list'] = taxonomy_get($post['listid']);
            $post['path'] = post_get_path($post['listid'],$post['path']);
            // 生成文章
            if ($make_post) post_create($post['postid']);
            // 文章内容
            if ($post['content'] && strpos($post['content'],'<!--pagebreak-->')!==false) {
                $contents = explode('<!--pagebreak-->', $post['content']);
                $content  = array_shift($contents);
            } else {
                $content  = $post['content'];
            }
            // 设置文章变量
            $vars = array(
                'zebra'    => ($i % ($zebra + 1)) ? '0' : '1',
                'postid'   => $post['postid'],
                'userid'   => $post['userid'],
                'author'   => $post['author'],
                'title'    => $post['title'],
                'views'    => '<script type="text/javascript" src="'.ROOT.'common/gateway.php?func=post_views&postid='.$post['postid'].'"></script>',
                'comment'  => '<script type="text/javascript" src="'.ROOT.'common/gateway.php?func=post_comment&postid='.$post['postid'].'"></script>',
                'people'   => '<script type="text/javascript" src="'.ROOT.'common/gateway.php?func=post_comment_people&postid='.$post['postid'].'"></script>',
                'digg'     => $post['digg'],
                'path'     => ROOT.$post['path'],
                'content'  => $content,
                'date'     => $post['datetime'],
                'edittime' => $post['edittime'],
                'keywords' => post_get_taxonomy($post['keywords']),
                'description' => $post['description'],
            );
            // 设置分类变量
            if (isset($post['list'])) {
                $vars['listid']     = $post['list']['taxonomyid'];
                $vars['listname']   = $post['list']['name'];
                $vars['listpath']   = ROOT.$post['list']['path'].'/';
                $vars['listcount']  = '<script type="text/javascript" src="'.ROOT.'common/gateway.php?func=taxonomy_count&listid='.$post['list']['taxonomyid'].'"></script>';
                if (isset($post['list']['meta'])) {
                    foreach((array)$post['list']['meta'] as $k=>$v) {
                        $vars['list.'.$k] = $v;
                    }
                }
            }
            // 清理数据
            tpl_clean($tpl);
            tpl_set_var($vars, $tpl);
            // 设置自定义字段
            if (isset($post['meta'])) {
                foreach((array)$post['meta'] as $k=>$v) {
                    tpl_set_var('post.'.$k, $v, $tpl);
                }
            }
            // 解析变量
            $inner.= tpl_parse($block['inner'], $block, $tpl); $i++;
        }
    } else {
        $inner = __('The page is in the making, please visit later ...');
    }
    // 生成标签块的唯一ID
    $b_guid = guid($block['tag']);
    // 把标签块替换成变量标签
    $html   = str_replace($block['tag'], '{$'.$b_guid.'}', $html);
}

// 所需要的标签和数据都不存在，不需要生成页面
//if ($i==0 && $page>1) return false;
// 清理模版内部变量
tpl_clean($tpl);
tpl_set_var($b_guid, $inner, $tpl);
tpl_set_var(array(
    'listid'        => $taxonomy['taxonomyid'],
    'listname'      => $taxonomy['name'],
    'listpath'      => ROOT.$taxonomy['path'].'/',
    'count'         => '<script type="text/javascript" src="'.ROOT.'common/gateway.php?func=taxonomy_count&listid='.$taxonomy['taxonomyid'].'"></script>',
    'guide'         => system_category_guide($taxonomy['taxonomyid']),
    'title'         => $taxonomy['name'],
    'keywords'      => post_get_taxonomy($taxonomy['keywords']),
    'description'   => $taxonomy['description'],
), $tpl);
// 设置自定义字段
if (isset($taxonomy['meta'])) {
    foreach((array)$taxonomy['meta'] as $k=>$v) {
        tpl_set_var('list.'.$k, $v, $tpl);
    }
}
$html = tpl_parse($html, $tpl);
echo $html;
// 生成的文件路径
//$file = ABS_PATH.'/'.$taxonomy['path'].'/index' . ($page==1 ? '' : $page) . $suffix;
// 创建目录
//mkdirs(dirname($file));
// 保存文件
//return file_put_contents($file,$html);
